<template>
  <div class="dormitory-apply">
    <div class="header">
      <router-link to="/main/wuye/dormitory/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>宿舍申请</h2>
    </div>

    <div class="content">
      <el-form :model="formData" ref="form" label-width="120px" class="application-form">
        <el-form-item label="申请编号">
          <el-input v-model="formData.applyNo" disabled></el-input>
        </el-form-item>

        <el-form-item label="申请人">
          <el-input v-model="formData.applicant"></el-input>
        </el-form-item>

        <el-form-item label="所属部门">
          <el-input v-model="formData.department"></el-input>
        </el-form-item>

        <el-form-item label="职位">
          <el-input v-model="formData.position"></el-input>
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>

        <el-form-item label="申请类型">
          <el-select v-model="formData.applyType">
            <el-option label="新员工申请" value="新员工申请"></el-option>
            <el-option label="调宿申请" value="调宿申请"></el-option>
            <el-option label="续住申请" value="续住申请"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="期望入住时间">
          <el-date-picker v-model="formData.expectedTime" type="date"></el-date-picker>
        </el-form-item>

        <el-form-item label="预计住宿时长">
          <el-input-number v-model="formData.duration" :min="1"></el-input-number>
          <span class="unit">月</span>
        </el-form-item>

        <el-form-item label="宿舍类型">
          <el-radio-group v-model="formData.roomType">
            <el-radio label="单人间">单人间</el-radio>
            <el-radio label="双人间">双人间</el-radio>
            <el-radio label="四人间">四人间</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="特殊要求">
          <el-input type="textarea" v-model="formData.requirements" rows="3"></el-input>
        </el-form-item>

        <el-form-item label="申请原因">
          <el-input type="textarea" v-model="formData.reason" rows="4"></el-input>
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="submitForm" :loading="submitting">提交申请</el-button>
            <el-button type="success" icon="el-icon-menu" @click="showList">申请列表</el-button>
          <el-button @click="resetForm">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表对话框 -->
    <el-dialog title="宿舍申请列表" :visible.sync="listDialogVisible" width="80%">
      <div class="filter-section">
        <el-input
          v-model="searchQuery"
          placeholder="请输入申请人/部门"
          style="width: 200px"
          clearable
          @keyup.enter.native="handleSearch">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="handleSearch">
        </el-date-picker>
      </div>
      
      <el-table :data="applyList" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="applicant" label="申请人" width="120"></el-table-column>
        <el-table-column prop="department" label="所属部门" width="150"></el-table-column>
        <el-table-column prop="dormitoryType" label="宿舍类型" width="120"></el-table-column>
        <el-table-column prop="applyDate" label="申请日期" width="120"></el-table-column>
        <el-table-column prop="expectedDate" label="预计入住日期" width="120"></el-table-column>
        <el-table-column prop="reason" label="申请原因" min-width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewDetail(scope.row)">查看</el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="cancelApply(scope.row)"
              v-if="scope.row.status === '待审批'">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      submitting: false,
      formData: {
        applyNo: this.generateApplyNo(),
        applicant: '',
        department: '',
        position: '',
        phone: '',
        applyType: '',
        expectedTime: '',
        duration: 6,
        roomType: '',
        requirements: '',
        reason: ''
      },
      rules: {
        applicant: [
          { required: true, message: '请输入申请人', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请输入所属部门', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        applyType: [
          { required: true, message: '请选择申请类型', trigger: 'change' }
        ],
        expectedTime: [
          { required: true, message: '请选择期望入住时间', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '请输入预计住宿时长', trigger: 'blur' },
          { type: 'number', min: 1, message: '住宿时长必须大于0', trigger: 'blur' }
        ],
        roomType: [
          { required: true, message: '请选择宿舍类型', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入申请原因', trigger: 'blur' },
          { min: 10, message: '申请原因不能少于10个字符', trigger: 'blur' }
        ]
      },
      listDialogVisible: false,
      searchQuery: '',
      dateRange: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      applyList: [
        {
          applicant: '张三',
          department: '技术部',
          dormitoryType: '双人间',
          applyDate: '2024-03-20',
          expectedDate: '2024-04-01',
          reason: '新入职员工住宿申请',
          status: '待审批'
        },
        {
          applicant: '李四',
          department: '销售部',
          dormitoryType: '单人间',
          applyDate: '2024-03-21',
          expectedDate: '2024-04-05',
          reason: '原宿舍到期更换申请',
          status: '已审批'
        }
      ]
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true
            
            // 调用后端接口
            const response = await this.$http.post('/api/dormitory-apply/submit', this.formData)
            
            this.$message.success('宿舍申请提交成功')
            this.$router.push('/main/wuye/dormitory/process')
          } catch (error) {
            const errorMsg = error.response?.data || '提交失败，请稍后重试'
            this.$message.error(errorMsg)
          } finally {
            this.submitting = false
          }
        } else {
          this.$message.warning('请填写完整的申请信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.applyNo = this.generateApplyNo()
      this.formData.duration = 6
    },
    generateApplyNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `SS${year}${month}${day}${random}`
    },
    showList() {
      this.listDialogVisible = true;
      this.loadApplyList();
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadApplyList();
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadApplyList();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadApplyList();
    },
    
    loadApplyList() {
      let filteredList = [...this.applyList];
      
      if (this.searchQuery) {
        filteredList = filteredList.filter(item => 
          item.applicant.includes(this.searchQuery) ||
          item.department.includes(this.searchQuery)
        );
      }
      
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        filteredList = filteredList.filter(item => {
          const itemDate = new Date(item.applyDate);
          return itemDate >= startDate && itemDate <= endDate;
        });
      }
      
      this.total = filteredList.length;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.applyList = filteredList.slice(start, end);
    },
    
    getStatusType(status) {
      const map = {
        '待审批': 'warning',
        '已审批': 'success',
        '已驳回': 'danger'
      };
      return map[status] || 'info';
    },
    
    viewDetail(row) {
      // TODO: 实现查看详情功能
      console.log('查看详情', row);
    },
    
    cancelApply(row) {
      this.$confirm('确认取消该申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用取消API
        this.$message.success('取消成功');
        this.loadApplyList();
      }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.dormitory-apply {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }

  .form-actions {
    display: flex;
    gap: 15px;
    justify-content: center;

    .el-button {
      min-width: 100px;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 
        }
      ]
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true
            
            // 调用后端接口
            const response = await this.$http.post('/api/dormitory-apply/submit', this.formData)
            
            this.$message.success('宿舍申请提交成功')
            this.$router.push('/main/wuye/dormitory/process')
          } catch (error) {
            const errorMsg = error.response?.data || '提交失败，请稍后重试'
            this.$message.error(errorMsg)
          } finally {
            this.submitting = false
          }
        } else {
          this.$message.warning('请填写完整的申请信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.applyNo = this.generateApplyNo()
      this.formData.duration = 6
    },
    generateApplyNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `SS${year}${month}${day}${random}`
    },
    showList() {
      this.listDialogVisible = true;
      this.loadApplyList();
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadApplyList();
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadApplyList();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadApplyList();
    },
    
    loadApplyList() {
      let filteredList = [...this.applyList];
      
      if (this.searchQuery) {
        filteredList = filteredList.filter(item => 
          item.applicant.includes(this.searchQuery) ||
          item.department.includes(this.searchQuery)
        );
      }
      
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        filteredList = filteredList.filter(item => {
          const itemDate = new Date(item.applyDate);
          return itemDate >= startDate && itemDate <= endDate;
        });
      }
      
      this.total = filteredList.length;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.applyList = filteredList.slice(start, end);
    },
    
    getStatusType(status) {
      const map = {
        '待审批': 'warning',
        '已审批': 'success',
        '已驳回': 'danger'
      };
      return map[status] || 'info';
    },
    
    viewDetail(row) {
      // TODO: 实现查看详情功能
      console.log('查看详情', row);
    },
    
    cancelApply(row) {
      this.$confirm('确认取消该申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用取消API
        this.$message.success('取消成功');
        this.loadApplyList();
      }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.dormitory-apply {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }

  .form-actions {
    display: flex;
    gap: 15px;
    justify-content: center;

    .el-button {
      min-width: 100px;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 
        }
      ]
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true
            
            // 调用后端接口
            const response = await this.$http.post('/api/dormitory-apply/submit', this.formData)
            
            this.$message.success('宿舍申请提交成功')
            this.$router.push('/main/wuye/dormitory/process')
          } catch (error) {
            const errorMsg = error.response?.data || '提交失败，请稍后重试'
            this.$message.error(errorMsg)
          } finally {
            this.submitting = false
          }
        } else {
          this.$message.warning('请填写完整的申请信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.applyNo = this.generateApplyNo()
      this.formData.duration = 6
    },
    generateApplyNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `SS${year}${month}${day}${random}`
    },
    showList() {
      this.listDialogVisible = true;
      this.loadApplyList();
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadApplyList();
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadApplyList();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadApplyList();
    },
    
    loadApplyList() {
      let filteredList = [...this.applyList];
      
      if (this.searchQuery) {
        filteredList = filteredList.filter(item => 
          item.applicant.includes(this.searchQuery) ||
          item.department.includes(this.searchQuery)
        );
      }
      
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        filteredList = filteredList.filter(item => {
          const itemDate = new Date(item.applyDate);
          return itemDate >= startDate && itemDate <= endDate;
        });
      }
      
      this.total = filteredList.length;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.applyList = filteredList.slice(start, end);
    },
    
    getStatusType(status) {
      const map = {
        '待审批': 'warning',
        '已审批': 'success',
        '已驳回': 'danger'
      };
      return map[status] || 'info';
    },
    
    viewDetail(row) {
      // TODO: 实现查看详情功能
      console.log('查看详情', row);
    },
    
    cancelApply(row) {
      this.$confirm('确认取消该申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用取消API
        this.$message.success('取消成功');
        this.loadApplyList();
      }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.dormitory-apply {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }

  .form-actions {
    display: flex;
    gap: 15px;
    justify-content: center;

    .el-button {
      min-width: 100px;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 
        }
      ]
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true
            
            // 调用后端接口
            const response = await this.$http.post('/api/dormitory-apply/submit', this.formData)
            
            this.$message.success('宿舍申请提交成功')
            this.$router.push('/main/wuye/dormitory/process')
          } catch (error) {
            const errorMsg = error.response?.data || '提交失败，请稍后重试'
            this.$message.error(errorMsg)
          } finally {
            this.submitting = false
          }
        } else {
          this.$message.warning('请填写完整的申请信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.applyNo = this.generateApplyNo()
      this.formData.duration = 6
    },
    generateApplyNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `SS${year}${month}${day}${random}`
    },
    showList() {
      this.listDialogVisible = true;
      this.loadApplyList();
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadApplyList();
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadApplyList();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadApplyList();
    },
    
    loadApplyList() {
      let filteredList = [...this.applyList];
      
      if (this.searchQuery) {
        filteredList = filteredList.filter(item => 
          item.applicant.includes(this.searchQuery) ||
          item.department.includes(this.searchQuery)
        );
      }
      
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        filteredList = filteredList.filter(item => {
          const itemDate = new Date(item.applyDate);
          return itemDate >= startDate && itemDate <= endDate;
        });
      }
      
      this.total = filteredList.length;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.applyList = filteredList.slice(start, end);
    },
    
    getStatusType(status) {
      const map = {
        '待审批': 'warning',
        '已审批': 'success',
        '已驳回': 'danger'
      };
      return map[status] || 'info';
    },
    
    viewDetail(row) {
      // TODO: 实现查看详情功能
      console.log('查看详情', row);
    },
    
    cancelApply(row) {
      this.$confirm('确认取消该申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用取消API
        this.$message.success('取消成功');
        this.loadApplyList();
      }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.dormitory-apply {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }

  .form-actions {
    display: flex;
    gap: 15px;
    justify-content: center;

    .el-button {
      min-width: 100px;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}